import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import '../../utils/eventbus.dart';
import '../../utils/http.dart';
import '../../utils/toast.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {
    "avatar": "",
    "nickName": "",
  };

  final TextEditingController _nicknameController = TextEditingController();

  editNickname() async {
    String nickname = _nicknameController.text;
    if (nickname.isEmpty) {
      ToastUtil.showError('昵称不能为空');
      print('昵称不能为空');
    }
    if (nickname.length > 10) {
      ToastUtil.showError('昵称长度不能超过10');
    }
    try {
      var res = await http.put('/userInfo', data: {'nickName': nickname});
      eventBus.fire(RefreshMine());
      ToastUtil.showSuccess('昵称修改成功');
      print(res);
    } catch (e) {
      ToastUtil.showError('网络出现异常${e}');
    }
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _nicknameController.text = userInfo['nickName'] ?? '';
    });
  }

  // 从相机或相册中选择图片
  selectAvatar() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 200,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {
                    _pickImageFromCamera();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () {
                    _pickImageFromGallery();
                  },
                )
              ]));
        });
  }

  Future<void> _pickImageFromCamera() async {
    ImagePicker picker = ImagePicker();
    final XFile? photo = await picker.pickImage(source: ImageSource.camera);
    if (photo != null) {
      print(photo?.path);
    }
  }

  Future<void> _pickImageFromGallery() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      print(pickedFile.path);
      try {
        // 1.包装FormData对象
        FormData fd = FormData.fromMap({
          "file": kIsWeb
              ? MultipartFile.fromBytes(
                  await XFile(pickedFile.path).readAsBytes(),
                  filename: 'avatar.jpg',
                  contentType: DioMediaType('image', 'jpeg'),
                )
              : await MultipartFile.fromFile(pickedFile.path),
          "type": "avatar"
        });
        //   2.上传接口
        var res = await http.post('/upload', fd);
        if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
        setState(() {
          userInfo['avatar'] = res['data']['url'];
        });
        ToastUtil.showSuccess('上传头像成功');
        eventBus.fire(RefreshMine());
      } finally {
        //     Navigator.pop(context);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        selectAvatar();
                      },
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: userInfo['avatar'] != null
                              ? Image.network(userInfo['avatar'],
                                  width: 30, height: 30)
                              : Image.asset('assets/images/avatar_1.jpg',
                                  width: 30, height: 30)),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nicknameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                  onEditingComplete: () {
                    editNickname();
                  },
                ),
              ),
              Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
